
package com.bw.lib_common.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bw.lib_common.entity.BaseEntity
import com.bw.lib_common.model.BaseRepository

import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob



/**
 * 基础的ViewModel
 */
open abstract class BaseViewModel2<Repo: BaseRepository<*>>:ViewModel(){


    private val handler = CoroutineExceptionHandler { _, exception ->
        Log.e("Error", "Exception===>"+exception.message)
        mErrorLiveData.postValue("网络请求异常！")
    }

    //Dispatchers协程调度器，IO代表在子线程中开启协程，MAIN代表在主线程中开启协程，DEFAULT代表在业务调用的线程中开启协程，Unconfined代表没有特殊指定哪个线程中开启协程
    protected val mViewModelScope = CoroutineScope(Dispatchers.IO + SupervisorJob() + handler)



    //错误信息提示
    val mErrorLiveData  = MutableLiveData<String>()
    //数据获取成功
    val mSuccessLiveData  = MutableLiveData<BaseEntity>()

    protected val mRepository: Repo

    init {
        mRepository = createRepository()
    }

    //创建仓库
    protected abstract fun createRepository(): Repo

}